#!/usr/bin/python

#
# Flo's Proxy Validator
# Nov 2010 Copyright (c) Florian Lerch - CoffeeReptile@gmail.com
#
# This program is free software licensed with the GNU Public License Version 2.

import urllib2
import urllib
import socket
import re
import optparse
import sys

class proxy_checker():
	def __init__(self):
		pass	
	def set_timeout(self,timeout): socket.setdefaulttimeout(timeout)
	def read_proxys(self,proxy_src):
		regex_script = re.compile(r'(\d+\.\d+\.\d+\.\d+:\d+)')
		proxy_servers = []
		for proxy_server in regex_script.findall(proxy_src):
    			proxy_servers.append(proxy_server)
		return proxy_servers
	def check_proxy(Self,proxy):
		proxy = urllib2.ProxyHandler({'http':proxy})
    		opener = urllib2.build_opener(proxy,urllib2.HTTPHandler)
    		urllib2.install_opener(opener)
    		try:
        		connection = urllib2.urlopen("http://www.google.de/intl/de/about.html")
        		content = connection.read()
        		if "pageTracker._trackPageview('de-de');" in str(content):
			 	return 1	#Verbindung erfolgreich
        		else:
            			return 0	#Keine Verbindung zu google
		except KeyboardInterrupt:
			return 3		#Keyobard Interrupt
    		except:
        		return 2	#Keine Verbindugn zum Proxy

if __name__ == "__main__":
	parser = optparse.OptionParser(description='Will check your proxylist.')
	parser.add_option('-f', help="name of the textfile with proxy servers",dest="listname")
	parser.add_option('-t', help="maximum time to check each proxy",default=4,dest="timeout")
	(options, args) = parser.parse_args()
	
	check_process = proxy_checker()	
	check_process.set_timeout(int(options.timeout))
	proxys = check_process.read_proxys(open(options.listname,"r").read())
	
	good_proxys = []
	for proxy in proxys:
		try:
			print proxy
			result = check_process.check_proxy(proxy)
			if result == 1: 
				print "Successfull"
				good_proxys.append(proxy)
			if result == 0: 
				print "Cant connect to Google"
			if result == 2:
				print "Cant connect to proxyserver"
			if result == 3:
				raise KeyboardInterrupt
		except KeyboardInterrupt:
			sys.exit(0)
	print "Running Proxys:"
	for proxy in good_proxys: print proxy
	
	end = raw_input("Please press enter")

